package org.gdufe.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.gdufe.auth.service.UserService;
import org.gdufe.pojos.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

//自定义UserDetailService
@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserService userService;
    //返回数据库中的正确用户信息，在AuthenticationProvider中进行认证
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        R r = userService.selectByUsername(username);
        if (r.getCode()==500){
            //todo: 全局异常处理
            throw new RuntimeException("用户名不存在");
        }
        org.gdufe.pojos.pojo.User user = (org.gdufe.pojos.pojo.User) r.getData();
        String authorities1 = user.getAuthorities();
        System.out.println(authorities1);
        List<String> authoritieslist = JSON.parseArray(authorities1,String.class);
        String[] authorities = authoritieslist.toArray(new String[]{});


        username=username;//可以修改为json,用来存储跟多信息
        String password=user.getPassword();

        return User.withUsername(username).password(password).authorities(authorities).build();
    }


}
